A good answer might be:

The completed program is given below.

Using a Constructor in a Declaration

Here is the complete program with the blanks filled in as suggested.


class StringTester
{

  public static void main ( String[] args )
  {
    String str1;   // str1 is a reference to a String object.
    String str2;   // str2 is a reference to a second String object.

    int    len1 , len2 ;    // the length of str1 and the length of str2

    str1   = new String( "Green eggs") ; // create the first String

    str2   = new String( " and ham.")  ; // create the second String


    len1  = str1.length();    // get the length of the first string

    len2  = str2.length();    // get the length of the second string

    System.out.println("The combined length of both strings is " +
        (len1 + len2) + " characters" );
  }
}

This is a "wordy" version of the program. An object can be created in a variable declaration. For example the following would work:

String str1 = new String("Green eggs");
String str2 = new String(" and ham.");

There is an even shorter way to do this, but it works only for String objects:

String str1 =  "Green eggs";
String str2 =  " and ham.";

The new operation still happens behind the scenes; this way is just "shorthand" for the longer way. For other classes you need to use the new Constructor() way of creating an object.

QUESTION 17:

Which of the following are correct?

String ant = "It was a dark and stormy night."
String bat = new( "A shot rang out in the dark." );
int    cat = "123";
double dog = 45.69;